const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { UnauthorizedError } = require('../utils/errors');
const { failureResponse } = require('../utils/responses')

module.exports = async (req, res, next) => {
  try {
    const { token } = req.headers;
    if (!token) {
      throw new UnauthorizedError('请登录后再试')
    }

    const { userId } = jwt.verify(token, process.env.SECRET);
    const user = await User.findByPk(userId);
    if (!user) {
      throw new UnauthorizedError('用户不存在')
    }
    if (user.role !== 100) {
      throw new UnauthorizedError('您没有权限使用当前接口')
    }
    // 将用户信息挂载到请求对象上，后续中间件可以直接使用req.user获取当前登录的用户信息
    req.user = user;
    next()
  } catch(error) {
    failureResponse(res, error)
  }
}